<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Chat</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <!-- Marked.js for Markdown parsing -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8f9fa;
        }

        .chat-container {
            height: 600px;
            overflow-y: auto;
            padding: 15px;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            background-color: #fff;
        }

        .chat-message {
            padding: 10px 15px;
            margin-bottom: 10px;
            border-radius: 8px;
            max-width: 80%;
        }

        .user-message {
            background-color: #e2f1ff;
            margin-left: auto;
            text-align: right;
        }

        .model-message {
            background-color: #f0f0f0;
            margin-right: auto;
        }

        .input-group {
            margin-top: 15px;
        }

        .sse-status {
            font-size: 0.8rem;
            color: #6c757d;
        }

        think {
            color: #666;
            font-size: 10px;
        }
    </style>
</head>

<body>
<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow">
                <div class="card-header bg-primary text-white">
                    <h3 class="text-center mb-0">SSE Chat</h3>
                    <div class="sse-status text-center" id="sse-status">Disconnected</div>
                    <!-- 移除连接按钮 -->
                </div>
                <div class="card-body">
                    <div id="sse-think"></div>
                    <div id="chat-container" class="chat-container mb-3">
                        <!-- Chat messages will be added here -->
                    </div>

                    <div class="input-group">
                        <input type="text" id="input-question" class="form-control" value="你是谁"
                               placeholder="Ask your question...">
                        <button id="send-question" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bootstrap JS Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function () {
        let accumulatedContent = '';
        let currentMessageDiv = null;

        // Update SSE connection status
        function updateStatus(status) {
            $('#sse-status').text(status);
        }

        // 封装发送消息的函数
        function sendQuestion() {
            const question = $('#input-question').val().trim();
            if (question) {
                // Add user message
                $('#chat-container').append(
                    $('<div class="chat-message user-message"></div>').text(question)
                );

                // Reset for new response
                currentMessageDiv = null;
                accumulatedContent = '';

                // 创建新的 SSE 连接
                const eventSource = new EventSource(`http://localhost:3000/chat-sse?message=${encodeURIComponent(question)}`, {withCredentials: false});

                updateStatus('Connecting...');

                eventSource.onopen = function () {
                    updateStatus('Connected');
                };

                eventSource.onclose = function () {
                    console.log('Connection closed normally');
                    updateStatus('Disconnected');
                };

                eventSource.onerror = function (e) {
                    updateStatus('Error: ' + e.message);
                    console.log("onerror", e);
                    console.log("onerror", eventSource);
                    updateStatus('Disconnected');
                    eventSource.close();
                };

                eventSource.addEventListener('message', function (e) {
                    const data = e.data;
                    const content = JSON.parse(data).content || "";
                    //$("#sse-think").append(content)
                    if (!currentMessageDiv) {
                        currentMessageDiv = $('<div class="chat-message model-message"></div>');
                        $('#chat-container').append(currentMessageDiv);
                        accumulatedContent = '';
                    }
                    accumulatedContent += content;
                    console.log("accumulatedContent", accumulatedContent)
                    //currentMessageDiv.text(accumulatedContent);
                    currentMessageDiv.html(marked.parse("<div>" + accumulatedContent + "</div>"))
                    scrollToBottom();
                });

                scrollToBottom();
            }
        }

        // Send question button
        $('#send-question').on('click', sendQuestion);

        // 监听输入框的 keypress 事件
        $('#input-question').on('keypress', function (e) {
            if (e.which === 13) { // 13 是回车键的 keyCode
                e.preventDefault(); // 阻止表单默认提交行为
                sendQuestion();
            }
        });

        function scrollToBottom() {
            const chatContainer = document.getElementById('chat-container');
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    });
</script>

</body>

</html>